// pages/sponsor/sponsor.js
import { request } from "../../utils/index.js";
import { areaList} from "../../utils/areaList.js";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseUrl:getApp().globalData.baseUrl,
    imgUrl: getApp().globalData.baseUrl + "/uploads/",
    areaList:{},  // 选中省市区数据
    province:"", // 省名称
    province_id:"", // 省id
    city:"", // 市名称
    city_id:"", // 市id
    district:"", // 区名称
    district_id:"", // 区id
    detail:"", // 详细地址
    postcode:"", // 邮编
    school:"", // 学校
    association:"", // 社团名称
    name:"", // 联系人姓名
    phone:"", // 联系人手机
    email:"", // 邮箱
    wechat:"", // 微信
    activityList:["文艺汇演","论坛讲座","体育活动","晚会典礼","营销大赛","迎新招新","其他"],
    activity_type:1, // 活动类型
    activity_type_text:"", // 选中活动类型
    start_date:"", // 开始时间
    end_date:"", // 结束时间
    sponsorList:["礼品赞助","资金赞助","冠名赞助","物资赞助","其他"],
    sponsor_type:1, // 赞助类型
    sponsor_type_text:"", // 选中赞助类型
    is_media:1, // 是否有官方媒体
    mediaText:"", // 选中官方媒体
    mediaList:["否","是"],
    remark:"", // 备注
    chooseImgs:"", // 附件选中的图片
    file:"", // 附件
    type:0, // 弹窗类型
    currentDate: new Date().getTime(),
    minDate: new Date().getTime(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      return value;
    },

  },

  // 详细地址
  onChangeAddress(event){
    this.setData({detail:event.detail})
  },
  // 邮编
  onChangeCode(event){
    this.setData({postcode:event.detail})
  },
  // 学校
  onChangeSchool(event) {
    this.setData({school:event.detail})
  },
  // 社团名称
  onChangeSponsorName(event){
    this.setData({association:event.detail})
  },
  // 联系人姓名
  onChangeName(event){
    this.setData({name:event.detail})
  },
  // 联系人手机
  onChangePhone(event){
    this.setData({phone:event.detail})
  },
  // 邮箱
  onChangeEmail(event){
    this.setData({email:event.detail})
  },
  // 微信号
  onChangeWX(event){
    this.setData({wechat:event.detail})
  },
  // 备注
  onChangeNote(event){
    this.setData({remark:event.detail})
  },

  // 弹窗
  showPopup(event) {
    console.log(event)
    var type = event.currentTarget.dataset.index;
    this.setData({type:type,show: true});
  },

  onClose() {
    this.setData({ show: false });
  },

  onInput(event) {
    this.setData({
      currentDate: event.detail,
    });
  },
  
  // 点击确定
  onConfirm(event) {
    if (this.data.type == 0) { // 选择是否官方媒体
      console.log(event);
      this.setData({ show: false });
      var that = this;
      if (event.detail.values.length > 0) {
        for (let i = 0; i < event.detail.values.length; i++) {
          if(i == 0 ){
            var province_id = event.detail.values[0].code;
            var province = event.detail.values[0].name;
            that.setData({
              province_id:province_id,
              province:province,
            })
          }else if (i == 1) {
            var city_id = event.detail.values[1].code;
            var city = event.detail.values[1].name;
            that.setData({
              city_id:city_id,
              city:city
            })
          }else {
            var district_id = event.detail.values[2].code;
            var district = event.detail.values[2].name;
            that.setData({
              district_id:district_id,
              district:district
            })
          }
        }
      }
    }else if (this.data.type == 1) { // 选择活动类型
      const { value, index } = event.detail;
      if (index == 6) {
        this.setData({
          show:false,
          is_media:9,
          activity_type_text:value
        }) 
      }else {
        this.setData({
          show:false,
          is_media:index+1,
          activity_type_text:value
        }) 
      }
    }else if (this.data.type == 2) { // 选择开始时间
       var timeValue = this.timeFormat(new Date(event.detail), "yyyy-MM-dd");
      console.log(timeValue)
      this.setData({
        show:false,
        start_date:timeValue,
      })
    }else if (this.data.type == 3) { // 选择结束时间
      var timeValue = this.timeFormat(new Date(event.detail), "yyyy-MM-dd");
      console.log(timeValue)
      this.setData({
        show:false,
        end_date:timeValue,
      })
    }else if (this.data.type == 4) { // 赞助种类
      const { value, index } = event.detail;
      if (index == 4) {
        this.setData({
          show:false,
          sponsor_type:9,
          sponsor_type_text:value
        }) 
      }else {
        this.setData({
          show:false,
          sponsor_type:index+1,
          sponsor_type_text:value
        }) 
      }
  
    }else if (this.data.type == 5) { // 是否有官方媒体
      const { value, index } = event.detail;
      this.setData({
        show:false,
        is_media:index,
        mediaText:value
      }) 
    } 
  },

  // 时间戳转时间字符串
  timeFormat(date, fmt) {
    var o = {
      "M+": date.getMonth() + 1,                 //月份   
      "d+": date.getDate(),                    //日
      "h+": date.getHours(),                   //小时   
      "m+": date.getMinutes(),                 //分   
      "s+": date.getSeconds(),                 //秒   
      "q+": Math.floor((date.getMonth() + 3) / 3), //季度   
      "S": date.getMilliseconds()             //毫秒   
    };
    if (/(y+)/.test(fmt))
      fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
      if (new RegExp("(" + k + ")").test(fmt))
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
   
  },

  // 上传附件
  onChangeFile(){
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (result) => {
        console.log(result)
        this.setData({
          chooseImgs:result.tempFilePaths[0]
        })
        this.updataImg();
      }
    })
  },

   // 上传图片
   updataImg() {

    wx.showLoading({
      title: "正在上传中",
      mask: true
    });
    console.log(this.data.chooseImgs)

    var that = this;
      wx.uploadFile({
      filePath: that.data.chooseImgs,
      name: 'imgurl',
      url: that.data.baseUrl + '/api/base64Upload',
      header: {
        "Content-Type": "multipart/form-data",
        'Content-Type': 'application/json',
        'Authorization': 'Bearer '+wx.getStorageSync("token"),     
      },
      formData: { 

      },
     success: (result) => {
      console.log(result)
      var obj = JSON.parse(result.data); 
      that.setData({
        file:obj.images
      })
        wx.showToast({
        title: "上传成功",
        icon: 'success',
        });
      },
      fail:(err)=> {
        wx.showToast({
          title: "上传失败",
          icon: 'fail',
        });
      }
      
    })
  },


  // 提交
  onSubmit(){
    var that = this;
    request({ url: "/api/sponsor/create",data:{
      province_id: that.data.province_id,
      city_id: that.data.city_id,
      district_id:that.data.district_id,
      address: that.data.address,
      postcode: that.data.postcode,
      school:that.data.school,
      association: that.data.association,
      contacts_name: that.data.name,
      contacts_mobile:that.data.phone,
      contacts_email: that.data.email,
      contacts_wechat:that.data.wechat,
      activity_type:that.data.activity_type,
      start_date:that.data.start_date,
      end_date:that.data.end_date,
      sponsor_type:that.data.sponsor_type,
      is_media:that.data.is_media,
      remark:that.data.remark,
      file:that.data.file
    }})
    .then(result => {
      wx.showToast({
        title: result.msg,
        icon: 'none',
        duration:2000
      });
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({areaList:areaList})
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})